package com.jinzhi.jzapi.certificate.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.jzapi.certificate.pojo.OrgRolesListVo;
import com.jinzhi.jzweb.domain.CertificateProfileDO;
import com.jinzhi.jzweb.domain.ExaminationPointDO;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.domain.OrganizationRolesDO;
import com.jinzhi.jzweb.service.CertificateProfileService;
import com.jinzhi.jzweb.service.ExaminationPointService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.service.OrganizationRolesService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/organizion")
public class ApiOrganizionController extends BaseController {

    @Autowired
    private OrganizationRolesService organizationRolesService;

    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private UserService userService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private ExaminationPointService examinationPointService;
    @Autowired
    private UserRoleService userRoleService;


    /**
     * api小程序端-站点列表数据接口
     *
     * @Description: 站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selExaminationPoint")
    @Log("api小程序端-站点列表数据接口")
    @ApiOperation(value = "api小程序端-站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExaminationPoint(String current, String number, String name, String type) {
        Map map = new HashMap();
        map.put("name",name);
        if(StringUtils.isNotBlank(type)){
            map.put("type",Integer.parseInt(type));
        }else{
            map.put("type","");
        }
        Page<OrgRolesListVo> page = organizationRolesService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            OrgRolesListVo obj = (OrgRolesListVo) page.getRecords().get(i);
            if (obj.getProfileId() != null){
                String[] profilesId = obj.getProfileId().split(",");
                String returnK = null;
                for(int j = 0;j<profilesId.length;j++){
                    CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(profilesId[j]));
                    if (certificateProfileDO != null) {
                        if(returnK == null){
                            returnK = certificateProfileDO.getName();
                        }else{
                            returnK = returnK + "," + certificateProfileDO.getName();
                        }
                    }
                }
                obj.setProfileName(returnK);
            }
            list.add(obj);
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }


//    /**
//     * api小程序端-站点申请接口
//     *
//     * 暂时停用（2020-03-13，李总提出小程序不弄站点申请功能）
//     *
//     * @param token               Token令牌
//     * @param name                站点名称
//     * @param roleType            站点类型 （0培训机构，1实训基地，2考评站，3实习就业单位，4培训考试点，5考核站点）
//     * @param orgType             机构类型 （0企业、1机关、2事业单位、3社会团体、4其它组织机构）
//     * @param orgCode             机构代码
//     * @param address             单位/学校地址
//     * @param legalRepresentative 法人代表
//     * @param scopeOfBusiness     营业范围-企业申请时字段
//     * @param staffSize           员工数量-企业申请时字段
//     * @param staffArrangement    员工学历层次-企业申请时字段
//     * @param profileId           申请负责证书id
//     * @param contacts            联系人姓名
//     * @param contactsPost        联系人职务
//     * @param mobile              联系电话
//     * @param email               电子邮箱
//     * @param schoolNature        学校性质(0中职,1高职,2本科)-学校申请时字段
//     * @param url                 网址
//     * @param numberOfExaminees   考生数-学校申请时字段
//     * @param teacherResources    师资力量-学校申请时字段
//     * @param enclosure           附件
//     * @Description: 站点信息申请
//     * @return: com.jinzhi.common.utils.ApiResult<?>
//     * @author kl
//     * @Date: 2020-03-05
//     */
//    @PostMapping("/addExaminationPoint")
//    @Log("api小程序端-站点申请接口")
//    @ApiOperation(value = "api小程序端-站点申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @RequiresAuthentication
//    @Transactional
//    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
//    public ApiResult<?> addExaminationPoint(@RequestHeader(value = TOKEN_TAG, required = false) String token, String name, String roleType, String orgType, String orgCode, String address,
//                                            String legalRepresentative, String scopeOfBusiness, String staffSize, String staffArrangement, String profileId, String contacts, String contactsPost,
//                                            String mobile, String email, String schoolNature, String url, String numberOfExaminees, String teacherResources,
//                                            @RequestParam("enclosure") MultipartFile enclosure) {
//        //1.根据token获取用户登录数据
//        UserDO user = this.getClientUser(token);
//        if (null == user) {
//            return ApiResult.invalid();
//        }
//
//        //2.判断机构信息是否存在
//        EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
//        entityWrapper.eq("org_code", orgCode);
//        OrganizationNewsDO organizationNewsDOS = organizationNewsService.selectOne(entityWrapper);
//        OrganizationNewsDO organizationNewsDO1;
//        if (organizationNewsDOS != null) {
//            //3.判断机构角色表汇总是否存在该类型数据
//            Map map = new HashMap();
//            map.put("roleType", roleType);
//            map.put("orgId", organizationNewsDOS.getId());
//            Long id = organizationRolesService.selById(map);
//            if (id != null) {
//                //提示已申请
//                return ApiResult.build(ApiEnumError.EnrolmentError.getCode(), "已申请");
//            }
//            organizationNewsDO1 = organizationNewsDOS;
//        } else {
//            //3.新建机构实体，存入数据
//            OrganizationNewsDO organizationNewsDO = new OrganizationNewsDO();
//            organizationNewsDO.setName(name);//企业名称
//            organizationNewsDO.setOrgCode(orgCode);//机构代码
//            organizationNewsDO.setAddress(address);//单位/学校地址
//            organizationNewsDO.setLegalRepresentative(legalRepresentative);//法人代表
//            organizationNewsDO.setContacts(contacts);//联系人
//            organizationNewsDO.setContactsPost(contactsPost);//联系人职务
//            organizationNewsDO.setMobile(mobile);//联系电话
//            organizationNewsDO.setMailbox(email);//电子邮箱
//            organizationNewsDO.setUrl(url);//网站
//            organizationNewsDO.setCreaterId(user.getId());//创建人id
//            organizationNewsDO.setUpdaterId(user.getId());//更新人id
//            organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
//            organizationNewsDO.setType(Integer.parseInt(orgType));//机构类型（0企业、1机关、2事业单位、3社会团体、4其它组织机构）
//
//            //这里只有事业单位和企业两种
//            if (orgType.equals("0")) {
//                organizationNewsDO.setScopeOfBusiness(scopeOfBusiness);//营业范围
//                organizationNewsDO.setStaffSize(staffSize);//员工数量
//                organizationNewsDO.setStaffArrangement(staffArrangement);//员工学历层次
//            }
//            if(orgType.equals("2")){
//                organizationNewsDO.setTeacherResources(teacherResources);//师资力量
//                if (StringUtils.isNotBlank(schoolNature) && !schoolNature.equals("[object Null]")) {
//                    organizationNewsDO.setSchoolNature(Integer.parseInt(schoolNature));//学校性质(0中职,1高职,2本科)
//                } else {
//                    organizationNewsDO.setSchoolNature(0);//学校性质(0中职,1高职,2本科)
//                }
//                if(StringUtils.isNotBlank(numberOfExaminees) && numberOfExaminees.equals("[object Null]")){
//                    organizationNewsDO.setNumberOfExaminees(Integer.parseInt(numberOfExaminees));//考生数
//                }else{
//                    organizationNewsDO.setNumberOfExaminees(0);//考生数
//                }
//            }
//
//            boolean b = organizationNewsService.insert(organizationNewsDO);
//            if (!b) {
//                return ApiResult.fail();
//            }
//            organizationNewsDO1 = organizationNewsDO;
//        }
//
//        OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
//        organizationRolesDO.setProfileId(profileId);//证书概况id
//        organizationRolesDO.setRoleType(Integer.parseInt(roleType));//机构角色
//        organizationRolesDO.setOrgId(organizationNewsDO1.getId());//机构id
//        organizationRolesDO.setApplicantId(user.getId());//申请人id
//        organizationRolesDO.setApplicantDate(new Date());//申请时间or
//        String enclosures = "";
//        try {
//            enclosures = sysFileService.upload(enclosure.getBytes(), enclosure.getOriginalFilename());
//        } catch (IOException e) {
//            e.printStackTrace();
//            return ApiResult.build(ApiEnumError.FileUploadError.getCode(), ApiEnumError.FileUploadError.getMsg());
//        }
//        organizationRolesDO.setEnclosure(enclosures);//机构申请附件
//
//        boolean c = organizationRolesService.insert(organizationRolesDO);
//        if (c) {
//            return ApiResult.success();
//        } else {
//            return ApiResult.fail();
//        }
//    }

    /**
     * 考核站点申请
     * @param token
     * @param name
     * @param numberOfExaminees
     * @param enclosure
     * @param cachet
     * @param team
     * @param equipment
     * @param employer
     * @param state
     * @param province
     * @param profileName
     * @return
     */
    @Log("提交站点申请")
    @PostMapping("/addExaminationPoint")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "web端-站点申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<Object> addExaminationPoint(@RequestHeader(value = TOKEN_TAG, required = false) String token,String name, Integer numberOfExaminees,
                                          String enclosure , String cachet, String team, String equipment, String employer ,Integer state, String province,String profileName) {//profileType 0:幼儿照护  1:产后恢复
        UserDO userDO = this.getClientUser(token);
        if (userDO==null){
            ApiResult.invalid();
        }
        UserDO user = userService.selectById(userDO.getId());
        CertificateProfileDO certificateProfileDO=certificateProfileService.findOneByKv("name",profileName);
        int roleType=5;//幼儿照护考核站点
        if(profileName.equals("产后恢复职业技能等级证书")){
            roleType=6;//产后恢复考核站点
        }


        if (user.getOrgId() == null){
            OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("applicant_id" , user.getId(),"profile_id",certificateProfileDO.getId());
            if (orgRole != null) {
                //如果该机构不是考核站点则直接覆盖为考核站点申请，或是考核站点草稿状态则直接更新
                if ((orgRole.getRoleType()==5||orgRole.getRoleType()==6)&&(orgRole.getCheckerState() == 0 || orgRole.getCheckerState() == 1 || orgRole.getCheckerState() == 2)){
                    return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode(), ApiEnumError.STATION_POINT_INSERT.getMsg()+"1");
                }
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(orgRole.getOrgId());
                organizationNewsDO.setName(name);//企业名称
                organizationNewsDO.setCreaterId(user.getId());//创建人id
                organizationNewsDO.setUpdaterId(user.getId());//更新人id
                organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
                organizationNewsDO.setCachet(cachet);
                organizationNewsDO.setNumberOfExaminees(numberOfExaminees);//考生数
                organizationNewsDO.setTeam(team);
                organizationNewsDO.setEquipment(equipment);
                organizationNewsDO.setEmployer(employer);
                organizationNewsDO.setProvince(province);
                boolean b = organizationNewsService.updateById(organizationNewsDO);
                if (!b) {
                    return ApiResult.fail("提交失败！错误代码：AOCaep101");
                }
                orgRole.setRoleType(roleType);
                orgRole.setApplicantId(user.getId());//申请人id
                orgRole.setApplicantDate(new Date());//申请时间
                orgRole.setEnclosure(enclosure);//机构申请附件
                orgRole.setCheckerState(state);

                boolean c = organizationRolesService.updateById(orgRole);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep102");
                }

            }else {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.findOneByKv("name" , name);
                if (organizationNewsDO != null){
                    OrganizationRolesDO rolesDO= organizationRolesService.findOneByKv("org_id",organizationNewsDO.getId());
                 if(rolesDO!=null){
                     if(rolesDO.getCheckerState()!=4){
                         return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , "站点名称已经存在");
                     }
                 }

                }else {
                    organizationNewsDO = new OrganizationNewsDO();
                    organizationNewsDO.setName(name);//企业名称
                    organizationNewsDO.setCreaterId(user.getId());//创建人id
                    organizationNewsDO.setUpdaterId(user.getId());//更新人id
                    organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
                    organizationNewsDO.setCachet(cachet);
                    organizationNewsDO.setNumberOfExaminees(numberOfExaminees);//考生数
                    organizationNewsDO.setTeam(team);
                    organizationNewsDO.setEquipment(equipment);
                    organizationNewsDO.setEmployer(employer);
                    organizationNewsDO.setProvince(province);
                    boolean b = organizationNewsService.insert(organizationNewsDO);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep103");
                    }
                }

                OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
                organizationRolesDO.setRoleType(roleType);//机构角色
                organizationRolesDO.setOrgId(organizationNewsDO.getId());//机构id
                organizationRolesDO.setApplicantId(user.getId());//申请人id
                organizationRolesDO.setApplicantDate(new Date());//申请时间
                organizationRolesDO.setEnclosure(enclosure);//机构申请附件
                organizationRolesDO.setCheckerState(state);

                if(certificateProfileDO != null){
                    organizationRolesDO.setProfileId(certificateProfileDO.getId().toString());//默认幼儿照护证书
                }

                boolean c = organizationRolesService.insert(organizationRolesDO);
                if (c) {
                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep104");
                }

            }

        }else {
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
            if(organizationNewsDO==null||!organizationNewsDO.getCreaterId().equals(user.getId())){
                return ApiResult.fail("提交失败！错误代码：AOCaep105");
            }

            OrganizationRolesDO roles = organizationRolesService.findOneByKv("org_id",organizationNewsDO.getId());
            if(roles!=null){
                if(roles.getRoleType()!=5&&roles.getRoleType()!=6){
                    OrganizationNewsDO organization = organizationNewsService.selectById(roles.getOrgId());
                    organization.setName(name);//企业名称
                    organization.setCreaterId(user.getId());//创建人id
                    organization.setUpdaterId(user.getId());//更新人id
                    organization.setLeadingCadreId(user.getId());//负责人id
                    organization.setCachet(cachet);
                    organization.setNumberOfExaminees(numberOfExaminees);//考生数
                    organization.setTeam(team);
                    organization.setEquipment(equipment);
                    organization.setEmployer(employer);
                    organization.setProvince(province);
                    boolean b = organizationNewsService.updateById(organization);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep107");
                    }

                    roles.setApplicantId(user.getId());//申请人id
                    roles.setRoleType(roleType);
                    roles.setApplicantDate(new Date());//申请时间
                    roles.setEnclosure(enclosure);//机构申请附件
                    roles.setCheckerState(state);

                    boolean c = organizationRolesService.updateById(roles);
                    if (c) {

                        user.setOrgId(organizationNewsDO.getId());
                        user.setOrgName(organizationNewsDO.getName());
                        return ApiResult.success();
                    } else {
                        return ApiResult.fail("提交失败！错误代码：AOCaep108");
                    }
                }
            }

            OrganizationRolesDO rolesDO = organizationRolesService.findOneByKv("applicant_id",user.getId(),"role_type",roleType);
            if(rolesDO!=null){
                if(rolesDO.getCheckerState()==0||rolesDO.getCheckerState()==1||rolesDO.getCheckerState()==2)
                    return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , ApiEnumError.STATION_POINT_INSERT.getMsg()+"3");
                OrganizationNewsDO organization = organizationNewsService.selectById(rolesDO.getOrgId());
                organization.setName(name);//企业名称
                organization.setCreaterId(user.getId());//创建人id
                organization.setUpdaterId(user.getId());//更新人id
                organization.setLeadingCadreId(user.getId());//负责人id
                organization.setCachet(cachet);
                organization.setNumberOfExaminees(numberOfExaminees);//考生数
                organization.setTeam(team);
                organization.setEquipment(equipment);
                organization.setEmployer(employer);
                organization.setProvince(province);
                boolean b = organizationNewsService.updateById(organization);
                if (!b) {
                    return ApiResult.fail("提交失败！错误代码：AOCaep107");
                }

                rolesDO.setApplicantId(user.getId());//申请人id

                rolesDO.setApplicantDate(new Date());//申请时间
                rolesDO.setEnclosure(enclosure);//机构申请附件
                rolesDO.setCheckerState(state);

                boolean c = organizationRolesService.updateById(rolesDO);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep108");
                }
            }else{
                OrganizationNewsDO organization = organizationNewsService.findOneByKv("name" , name);
                if (organization != null){
                    OrganizationRolesDO organizationRole = organizationRolesService.findOneByKv("org_id",organization.getId(),"role_type",roleType);
                    if(organizationRole!=null&&organizationRole.getCheckerState()!=4)
                        return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , ApiEnumError.STATION_POINT_INSERT.getMsg());
                }else {
                    organization = new OrganizationNewsDO();
                    organization.setName(name);//企业名称
                    organization.setCreaterId(user.getId());//创建人id
                    organization.setUpdaterId(user.getId());//更新人id
                    organization.setLeadingCadreId(user.getId());//负责人id
                    organization.setCachet(cachet);
                    organization.setNumberOfExaminees(numberOfExaminees);//考生数
                    organization.setTeam(team);
                    organization.setEquipment(equipment);
                    organization.setEmployer(employer);
                    organization.setProvince(province);
                    boolean b = organizationNewsService.insert(organization);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep109");
                    }
                }

                OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
                organizationRolesDO.setRoleType(roleType);//机构角色
                organizationRolesDO.setOrgId(organizationNewsDO.getId());//机构id
                organizationRolesDO.setApplicantId(user.getId());//申请人id
                organizationRolesDO.setApplicantDate(new Date());//申请时间
                organizationRolesDO.setEnclosure(enclosure);//机构申请附件
                organizationRolesDO.setCheckerState(state);

                if(certificateProfileDO != null){
                    organizationRolesDO.setProfileId(certificateProfileDO.getId().toString());//默认幼儿照护证书
                }

                boolean c = organizationRolesService.insert(organizationRolesDO);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep111");

                }
            }

        }
    }

    @Log("提交编辑站点申请")
    @PostMapping("/saveStation")
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> saveStation(@RequestHeader(value = TOKEN_TAG, required = false) String token,String name, Integer numberOfExaminees,
                             String enclosure , String cachet, String team, String equipment, String employer ,String orgId , Integer state, String province) {
        UserDO user = this.getClientUser(token);
        if (user == null){
            return ApiResult.invalid();
        }
        OrganizationNewsDO orgNews = organizationNewsService.selectById(orgId);
        orgNews.setName(name);//企业名称
        orgNews.setCreaterId(user.getId());//创建人id
        orgNews.setUpdaterId(user.getId());//更新人id
        orgNews.setLeadingCadreId(user.getId());//负责人id
        orgNews.setCachet(cachet);
        orgNews.setNumberOfExaminees(numberOfExaminees);//考生数
        orgNews.setTeam(team);
        orgNews.setEquipment(equipment);
        orgNews.setEmployer(employer);
        orgNews.setProvince(province);

        boolean c = organizationNewsService.updateById(orgNews);

        UserDO userDo = userService.findOneByKv("orgId" , orgNews.getId());
        if (userDo != null){

            List<Long> roleIds = userRoleService.listRoleId(userDo.getId());
            if (roleIds != null && roleIds.size() > 0) {
                userDo.setroleIds(roleIds);
            } else {
                List<Long> list11 = new ArrayList<>();
                list11.add(56L);
                userDo.setroleIds(list11);
            }

            userDo.setOrgName(name);
            userService.updateById(userDo);
        }

        List<ExaminationPointDO> examPointList = examinationPointService.findByKv("org_id" , orgId);
        if (examPointList.size() != 0){
            for (ExaminationPointDO examinationPoint : examPointList){
                examinationPoint.setName(name);
            }
        }

        OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("role_type" , 5 , "org_id" , orgId);
        orgRole.setCheckerState(state);
        orgRole.setEnclosure(enclosure);
        organizationRolesService.updateById(orgRole);

        if (c) {
            return ApiResult.success();
        } else {
            return ApiResult.fail("提交失败，错误代码：AOCss101");
        }
    }
}
